from zope.interface import implements
from twisted.internet import interfaces, reactor
from twisted.internet.protocol import Factory, ClientFactory, ReconnectingClientFactory
from twisted.protocols.basic import LineReceiver
from time import time

class ContentProducer:
  implements(interfaces.IPushProducer)
  def __init__(self, protocol):
    self.protocol = protocol
    self.paused = False
    self.lineCount = 0
    self.startTime = None
    self.delay = 0.0
  def pauseProducing(self):
    print "ContentProducer paused"
    self.paused = True
  def resumeProducing(self):
    print "ContentProducer resuming"
    self.paused = False
    if not self.startTime:
      self.startTime = time()
    while not self.paused:
      self.protocol.transport.write("Hello world\r\n")
      self.lineCount += 1
      if self.lineCount % 1000 == 0:
        print "rate = %.2f lines / second" % (self.lineCount / (time()-self.startTime))
  def stopProducing(self):
    pass

class NodeProtocol(LineReceiver):

  def connectionMade(self):
    print "%s.connectionMade" % self.factory.name
    if self.factory.name == 'A':
      self.producer = ContentProducer(self)
      self.transport.registerProducer(self.producer, True)
      self.producer.resumeProducing()

  def lineReceived(self, line):
    print "%s.lineReceived(%s)" % (self.factory.name, line)

  def connectionLost(self, reason):
    print "%s.connectionLost(%s)" % (self.factory.name, reason)

class NodeFactory(Factory):
  protocol = NodeProtocol
  isServer = True
  def __init__(self, name):
    self.name = name

class NodeClientFactory(ClientFactory):
  protocol = NodeProtocol
  isServer = False
  def __init__(self, name):
    self.name = name
    self.retry_count = 0

class ANode:
  port = 2000 
  def __init__(self):
    """ it's a server """
    self.factory = NodeFactory("A")
    reactor.listenTCP(self.port, self.factory)

class BNode:
  def __init__(self):
    """ it's a client """
    self.factory = NodeClientFactory("B")
    reactor.connectTCP("localhost", ANode.port, self.factory)


